package org.cainiao.api.lark.impl.imperative.docs.board.thumbnail;

import lombok.RequiredArgsConstructor;
import org.cainiao.api.lark.imperative.docs.board.thumbnail.Thumbnail;
import org.cainiao.api.lark.impl.util.provider.LarkAccessTokenProvider;
import org.cainiao.api.lark.util.Util;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.WebClient;

import static org.cainiao.api.lark.util.Util.BOARD_MODULE_URI;

/**
 * 靠 RestOperations 切换 HTTP 客户端<br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@RequiredArgsConstructor
public class WebClientThumbnail implements Thumbnail {

    private final WebClient webClient;
    private final String baseUrl;
    /**
     * tenant_access_token 或 user_access_token
     */
    private final LarkAccessTokenProvider larkAccessTokenProvider;

    @Override
    public ResponseEntity<Resource> whiteboardImage(String whiteboardId) {
        String url = String.format("%s%s/whiteboards/%s/download_as_image", baseUrl, BOARD_MODULE_URI, whiteboardId);
        byte[] imageBytes = Util.getPngWithAccessToken(webClient, url, larkAccessTokenProvider)
            .retrieve()
            .bodyToMono(byte[].class)
            .block();
        if (imageBytes != null) {
            ByteArrayResource resource = new ByteArrayResource(imageBytes);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", "whiteboardImage.png");
            headers.setContentType(MediaType.IMAGE_PNG);
            return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
        }
        return ResponseEntity.notFound().build();
    }
}
